/**
 * Copyright (C) 2009 Matteo Merli <mm@merlimat.org>
 * 
 * $Id: JavaClassFactory.java 21 2009-01-12 17:30:19Z matteo.merli $
 * $URL: http://pxl-lang.googlecode.com/svn/trunk/src/main/old_code/JavaClassFactory.java $
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pxl.types;

import java.util.Map;

import pxl.Context;
import pxl.errors.ImportError;

import com.google.common.collect.Maps;

public class JavaClassFactory
{

    private Map<String, JavaClass> classCache = Maps.newConcurrentHashMap();

    private static JavaClassFactory instance = new JavaClassFactory();

    public static JavaClassFactory getInstance()
    {
        return instance;
    }

    public void importClass( String className )
    {
        JavaClass javaClass = getClassByName( className );
        Context.getInstance().put( javaClass.getName(), javaClass );
    }

    @SuppressWarnings ( "unchecked")
    public JavaClass getClassByName( String className )
    {
        JavaClass javaClass = null;

        javaClass = classCache.get( className );

        if ( javaClass != null )
        {
            return javaClass;
        }

        Class<Object> clazz = null;

        try
        {
            clazz = (Class<Object>) Class.forName( className );

        }
        catch ( ClassNotFoundException nfe )
        {
            throw new ImportError( "Class not found: '" + className + "'" );
        }
        catch ( ExceptionInInitializerError ie )
        {
            throw new ImportError( "Error initializing '" + className + "'" );
        }
        catch ( LinkageError le )
        {
            throw new ImportError( "Error linking '" + className + "'" );
        }

        javaClass = new JavaClass( clazz );
        classCache.put( className, javaClass );
        return javaClass;
    }

}
